<template>
  <div>
    <el-card>
      <div slot="header">
        <div>课程：</div>
        <div>阶段：</div>
        <div>课时：</div>
      </div>
      <el-form label-width="40px">
        <el-form-item label="视频">
          <input
            ref="video-file"
            type="file">
        </el-form-item>
        <el-form-item label="封面">
          <input
            ref="image-file"
            type="file"/>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="authUpload"
          >开始上传</el-button>
          <el-button>返回</el-button>
        </el-form-item>
        <el-form-item>
          <p>上传进度：{{uploadPercent}}%</p>
          <p v-if="isUploadSuccess">转码进度：{{isTransCodeSuccess?"完成":"正在处理请稍后"}}</p>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import { getuploadImage, getuploadVideo, transCode, transCodePercent } from '@/services/aliyun-upload'
export default Vue.extend({
  name: 'CourseVideo',
  props: {
    courseId: {
      type: [Number, String],
      required: true
    }
  },
  data () {
    return {
      uploader: null,
      imageURL: '',
      videoId: null,
      isUploadSuccess: false,
      isTransCodeSuccess: false,
      uploadPercent: 0
    }
  },
  computed: {
    videoFile ():any {
      return (this.$refs['video-file'] as any).files[0]
    },
    imageFile ():any {
      return (this.$refs['image-file'] as any).files[0]
    }
  },
  methods: {
    authUpload () {
      // 初始化上传状态
      this.isUploadSuccess = false
      this.isTransCodeSuccess = false
      this.uploadPercent = 0

      const uploader = this.uploader as any
      // 添加到上传列表,按顺序上传
      uploader.addFile(this.imageFile, null, null, null, '{"Vod":{}}')
      uploader.addFile(this.videoFile, null, null, null, '{"Vod":{}}')
      // 开始上传
      uploader.startUpload()
    },
    handleUpload () {
      this.uploader = new window.AliyunUpload.Vod({
        // userID，必填，只需有值即可。
        userId: '122',
        // 上传到视频点播的地域，默认值为'cn-shanghai'，
        // eu-central-1，ap-southeast-1
        region: '',
        // 分片大小默认1 MB，不能小于100 KB，此参数单位默认为 B
        partSize: 1048576,
        // 并行上传分片个数，默认5
        parallel: 5,
        // 网络原因失败时，重新上传次数，默认为3
        retryCount: 3,
        // 网络原因失败时，重新上传间隔时间，默认为2秒
        retryDuration: 2,
        // 开始上传
        onUploadstarted: async (uploadInfo:any) => {
          // console.log('onUploadstarted', uploadInfo)
          let uploadAuth
          // 1. 通过后端获取上传凭证
          if (uploadInfo.isImage) {
            const { data } = await getuploadImage()
            this.imageURL = data.data.imageURL
            uploadAuth = data.data
            console.log('imgdata', data)
          } else {
            const { data: videodata } = await getuploadVideo({
              fileName: uploadInfo.file.name,
              imageUrl: this.imageURL
            })
            this.videoId = videodata.data.videoId
            uploadAuth = videodata.data
            console.log('videodata', videodata)
          }
          // 2. 调用 uploader.setUploadAuthAndAddress 设置上传凭证
          (this.uploader as any).setUploadAuthAndAddress(
            uploadInfo, uploadAuth.uploadAuth, uploadAuth.uploadAddress, uploadAuth.imageId || uploadAuth.videoId)
          // 3. 确认上传凭证设置没问题，会开始上传进度，可以看log
          // 4. 全部上传结束调用 onUploadEnd 回调，在结束回调中进行转码操作
        },
        // 文件上传成功
        onUploadSucceed: function (uploadInfo:any) {
          console.log('onUploadSucceed', uploadInfo)
        },
        // 文件上传失败
        onUploadFailed: function (uploadInfo:any, code:any, message:any) {
          console.log('onUploadFailed', uploadInfo, code, message)
        },
        // 文件上传进度，单位：字节
        onUploadProgress: (uploadInfo:any, totalSize:any, loadedPercent:any) => {
          console.log('onUploadProgress', uploadInfo, totalSize, loadedPercent)
          if (!uploadInfo.isImage) {
            this.uploadPercent = Math.floor(loadedPercent * 100)
          }
        },
        // 上传凭证或STS token超时
        onUploadTokenExpired: function (uploadInfo:any) {
          console.log('onUploadTokenExpired', uploadInfo)
        },
        // 全部文件上传结束
        onUploadEnd: async (uploadInfo:any) => {
          console.log('onUploadEnd', uploadInfo)
          this.isUploadSuccess = true
          // 视频转码请求
          const { data } = await transCode({
            lessonId: this.$route.query.lessonId,
            coverImageUrl: this.imageURL, // img url
            fileName: this.videoFile.name, // 文件名
            fileId: this.videoId
          })
          console.log('请求转码', data)

          const timer = setInterval(async () => {
            const { data } = await transCodePercent(this.$route.query.lessonId)
            console.log('轮询转码', data.data)
            if (data.data === 100) {
              console.log('转码成功')
              this.isTransCodeSuccess = true
              window.clearInterval(timer)
            }
          }, 3000)
        }
      })
    }
  },
  created () {
    this.handleUpload()
  }
})
</script>

<style lang="scss" scoped>

</style>
